HTTP Status Code এবং Exception Handling কৌশল

Java Technologies - স্প্রিং বুট ক্লায়েন্ট (Spring Boot Client) - Error Handling এবং Exception Management
164

Spring Boot-এ REST API-এর মাধ্যমে HTTP স্ট্যাটাস কোড হ্যান্ডল এবং এক্সেপশন ম্যানেজ করার জন্য বিভিন্ন কৌশল রয়েছে। RestTemplate বা WebClient উভয়ের ক্ষেত্রেই নির্দিষ্ট কৌশল প্রয়োগ করা হয়।


HTTP Status Code এবং Exception Handling কেন গুরুত্বপূর্ণ?

  1. API রেসপন্স যাচাই করা:
    • ক্লায়েন্ট সঠিকভাবে জানবে যে সার্ভার রিকোয়েস্ট সফলভাবে হ্যান্ডেল করেছে কি না।
    • উদাহরণ: 200 OK, 201 Created, 404 Not Found, 500 Internal Server Error
  2. এক্সেপশন ম্যানেজ করা:
    • রিকোয়েস্ট ফেল হলে এর কারণ অনুসারে এক্সেপশন থ্রো এবং হ্যান্ডেল করা প্রয়োজন।

HTTP Status Code এর ধরন

১. 2xx (Success):

সফল রিকোয়েস্ট এবং রেসপন্স নির্দেশ করে।

  • 200 OK
  • 201 Created

২. 4xx (Client Errors):

ক্লায়েন্ট সাইড সমস্যার জন্য ব্যবহার হয়।

  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found

৩. 5xx (Server Errors):

সার্ভার সাইড সমস্যার জন্য ব্যবহার হয়।

  • 500 Internal Server Error
  • 503 Service Unavailable

RestTemplate: Exception Handling

RestTemplate-এ Custom Exception এবং HTTP Status Code হ্যান্ডল করার জন্য ResponseErrorHandler ব্যবহার করা হয়।

Custom ResponseErrorHandler তৈরি:

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        if (response.getStatusCode().is4xxClientError()) {
            // 4xx Errors
            throw new RuntimeException("Client Error: " + response.getStatusCode());
        } else if (response.getStatusCode().is5xxServerError()) {
            // 5xx Errors
            throw new RuntimeException("Server Error: " + response.getStatusCode());
        }
    }
}

RestTemplate-এ Custom Error Handler সেট করা:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    private final CustomResponseErrorHandler errorHandler;

    public RestTemplateConfig(CustomResponseErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(errorHandler); // Custom Error Handler সেট করা
        return restTemplate;
    }
}

RestTemplate-এ Exception Handling উদাহরণ:

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {

    private final RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData(String url) {
        try {
            return restTemplate.getForObject(url, String.class);
        } catch (RuntimeException e) {
            System.err.println("Error occurred: " + e.getMessage());
            throw e; // Exception পুনরায় থ্রো করা
        }
    }
}

WebClient: Exception Handling

WebClient-এ HTTP Status Code এবং Exception Handling করার জন্য onStatus এবং onError ব্যবহার করা হয়।

Exception Handling কৌশল:

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String fetchData(String url) {
        try {
            return webClient.get()
                    .uri(url)
                    .retrieve()
                    .onStatus(
                        status -> status.is4xxClientError(), // 4xx Errors হ্যান্ডল করা
                        clientResponse -> Mono.error(new RuntimeException("Client Error"))
                    )
                    .onStatus(
                        status -> status.is5xxServerError(), // 5xx Errors হ্যান্ডল করা
                        clientResponse -> Mono.error(new RuntimeException("Server Error"))
                    )
                    .bodyToMono(String.class)
                    .block();
        } catch (WebClientResponseException e) {
            System.err.println("Error response: " + e.getStatusCode());
            throw e;
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            throw e;
        }
    }
}

Global Exception Handling

Spring Boot-এ Global Exception Handler ব্যবহার করে এক্সেপশন হ্যান্ডল করা যায়। এটি সব API কলের জন্য প্রযোজ্য।

@RestControllerAdvice ব্যবহার:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Error: " + ex.getMessage());
    }

    @ExceptionHandler(WebClientResponseException.class)
    public ResponseEntity<String> handleWebClientResponseException(WebClientResponseException ex) {
        return ResponseEntity
                .status(ex.getStatusCode())
                .body("WebClient Error: " + ex.getMessage());
    }
}

Exception Logging

Spring Boot-এ এক্সেপশন লগ করার জন্য Logger ব্যবহার করা যেতে পারে:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ApiService {

    private static final Logger logger = LoggerFactory.getLogger(ApiService.class);
    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String fetchData(String url) {
        try {
            return webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();
        } catch (Exception e) {
            logger.error("Error fetching data: ", e);
            throw e;
        }
    }
}

উপসংহার

  1. RestTemplate এবং WebClient-এ এক্সেপশন হ্যান্ডল করা সহজ এবং কাস্টমাইজ করা যায়।
  2. Global Exception Handling ব্যবহার করে সব রিকোয়েস্টের জন্য একই রকম লজিক প্রয়োগ করা যায়।
  3. HTTP Status Code অনুযায়ী বিভিন্ন এক্সেপশন থ্রো করা ক্লায়েন্ট-সার্ভার যোগাযোগের ত্রুটি শনাক্তে সাহায্য করে।
  4. WebClient আধুনিক এবং নন-ব্লকিং হওয়ায় বড় স্কেল অ্যাপ্লিকেশনের জন্য বেশি কার্যকর।

এই কৌশলগুলো ব্যবহার করে আপনি একটি রিলায়েবল এবং ইফিশিয়েন্ট ক্লায়েন্ট তৈরি করতে পারবেন।

Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...